package xyz.lwm.lazycat.event;

import xyz.lwm.lazycat.utility.Pair;

import java.util.ArrayList;
import java.util.List;

/**
 * 内部事件处理 (勿用)
 *
 * @author lwm
 */
public abstract class Events {

    private static final List<Pair<Class<? extends Event>, EventHandler<?>>> HANDLERS = new ArrayList<>();

    /**
     * 订阅事件
     *
     * @param eventClass   事件类
     * @param eventHandler 时间处理器
     * @param <T>          事件类型
     */
    public static <T extends Event> void subscribe(Class<T> eventClass, EventHandler<T> eventHandler) {
        synchronized (HANDLERS) {
            HANDLERS.add(Pair.of(eventClass, eventHandler));
        }
    }

    /**
     * 发布事件
     *
     * @param e 事件
     */
    public static void publish(Event e) {
        if (e != null) {
            try {
                publish0(e);
            } catch (Throwable t) {
                if (t instanceof RuntimeException) {
                    throw (RuntimeException) t;
                } else {
                    throw new EventException("Publish event failed: " + e.getClass().getName(), t);
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    private static void publish0(Event e) throws Throwable {
        for (int i = 0; i < HANDLERS.size(); i++) {
            Pair<Class<? extends Event>, EventHandler<?>> p = HANDLERS.get(i);
            if (p.getLeft().isAssignableFrom(e.getClass())) {
                ((EventHandler<Event>) p.getRight()).onEvent(e);
            }
        }
    }

}
